import React from 'react';
import { Select, Tag } from '@teamix/ui';
import { ButtonIcon, Title } from '@alife/devops-ui';
import ListEmpty from 'atComponents/ListEmpty';
import sha1 from 'sha1';
import './index.scss';
import track from 'utils/track';
import { getProjectServices } from 'api';
import ListLoading from 'atComponents/ListLoading';
import { ENUM } from 'utils/constants.js';
import intl from '../../../../../../../../../../../locale';

const { mrTriggerMap } = ENUM;
export default class CommentList extends React.Component {
  constructor(props) {
    super(props);
    // 从overview页面跳转过来，会携带模式buidlId,否则取issues长度有值的第一个
    let filterId = props.curBuildId;

    const curBuilds = this.filterMrBuilds();
    if (curBuilds.length !== 0) {
      if (!props.curBuildId) {
        const issueBuilds = curBuilds.filter((item) => {
          const count =
            Number(item.blocker_count) + Number(item.major_count) + Number(item.critical_count);
          return count;
        });
        if (issueBuilds.length) {
          filterId = issueBuilds[0].id;
        } else {
          filterId = curBuilds[0].id;
        }
      }
    }

    this.state = {
      filterId: filterId || '',
      codeScan: null,
      settings: {},
    };

    this.getCodeScanOpenInfo();
  }

  color = { Major: 'blue', Critical: 'orange', Blocker: 'red' };

  classLevel = { Major: 'major', Critical: 'critical', Blocker: 'blocker' };

  componentDidMount() {
    // 定位,改用监听滚动
    const otherHeight = 51; // 导航 + 库tab
    const mrHeader = document.querySelector('.mr-detail-content-header');
    const mrHeaderHeight = mrHeader ? mrHeader.offsetHeight : 0;
    const container = document.querySelector('.codescan-list-container');
    if (container) {
      container.style.top = `${mrHeaderHeight + otherHeight}px`;
    }
    if (document.querySelector('.mr-detail-content-body ')) {
      document.querySelector('.mr-detail-content-body ').classList.add('hideScroll');
    }
  }

  componentWillUnmount() {
    const container = document.querySelector('.codescan-list-container');
    if (container) {
      container.scrollTop = 0;
    }
    if (document.querySelector('.mr-detail-content-body ')) {
      document.querySelector('.mr-detail-content-body ').classList.remove('hideScroll');
    }
  }

  getCodeScanOpenInfo() {
    getProjectServices()
      .then((result) => {
        const settings = result.integration_service_setting;

        // 服务开启且触发有mr_trigger
        const codeScan = Object.keys(settings).some((key) => {
          const item = settings[key];
          return item.enabled === true && item.mr_trigger;
        });

        this.setState({
          codeScan,
          settings,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  handleLineClick = (e, hash) => {
    e.preventDefault();
    window.location.hash = hash;
    // 面板不收起
    // this.props.updateData({
    //   isShowCodeScan: false,
    // });
  };

  renderList = () => {
    const { issueDetailList, commits, codeReviewDetail } = this.props;
    const { settings } = this.state;
    const curBuilds = this.filterMrBuilds();

    const data = {};
    const filterList = issueDetailList.filter((item) => {
      if (!this.state.filterId) {
        return item;
      }
      return item.build_result_id === this.state.filterId;
    });
    filterList.forEach((item) => {
      if (Object.keys(data).includes(item.file_name)) {
        data[item.file_name].push(item);
      } else {
        data[item.file_name] = [item];
      }
    });

    let curCodeScan = '';
    curBuilds.forEach((item) => {
      if (item.id === this.state.filterId) {
        curCodeScan = item.task_name;
      }
    });

    // 扫描接口返回，但当前服务未开启时
    let curKey = '';
    Object.keys(mrTriggerMap).forEach((key) => {
      if (mrTriggerMap[key] === curCodeScan) {
        curKey = key;
      }
    });

    if (!(settings[curKey] && settings[curKey].mr_trigger)) {
      return (
        <div className="codescan-list-empty">
          <ListEmpty
            image="none"
            content={intl.get(
              {
                id: 'code-assets.components.codeScan.CurcodescanDisabled',
                defaultMessage: '未开启{curCodeScan}',
              },
              { curCodeScan },
            )}
            description={intl.get({
              id: 'code-assets.components.codeScan.TheAdministratorCanEnableIntegration',
              defaultMessage: '管理员可在 设置-集成与服务 开启',
            })}
            size="small"
            type="card"
            className="no-btns"
          />
        </div>
      );
    }

    if (!Object.keys(data).length) {
      return (
        <div className="codescan-list-empty">
          <ListEmpty
            image="none"
            content={intl.get({
              id: 'code-assets.components.codeScan.NoProblem',
              defaultMessage: '暂无问题',
            })}
            description={intl.get({
              id: 'code-assets.components.codeScan.AwesomeContinueToWork',
              defaultMessage: '真棒，继续加油吧',
            })}
            size="small"
            type="card"
            className="no-btns"
          />
        </div>
      );
    }

    // 只涉及到最新,为right；
    const side = 'right';
    // commit传递最新的
    const { length } = commits;
    let range_context = '';
    if (commits.length) {
      range_context = `&from_commit=${commits[0].sha}&to_commit=${commits[length - 1].sha}`;
    }

    let codescanLength = 0;
    Object.keys(data).forEach((item) => {
      codescanLength += data[item].length;
    });
    return (
      <div className="codescan-list">
        <div className="codescan-list-tips">
          <img
            className="codescan-list-yundou"
            src="https://img.alicdn.com/tfs/TB1WYSpIQL0gK0jSZFtXXXQCXXa-400-401.png"
            alt=""
          />
          {intl.get({
            id: 'code-assets.components.codeScan.ForYouDetect',
            defaultMessage: '已为你检测出',
          })}
          {codescanLength}
          {intl.get({
            id: 'code-assets.components.codeScan.AQuestionPayAttentionTo',
            defaultMessage: '个问题，关注一下吧',
          })}
        </div>
        {Object.keys(data).map((item) => {
          const issues = data[item];
          const curIssues = [];
          issues.forEach((issue) => {
            // 根据title将同类问题显示在一起，将行号集中起来
            const sameTitleIndex = curIssues.findIndex((cur) => {
              return cur.title === issue.title;
            });
            if (sameTitleIndex === -1) {
              curIssues.push({
                ...issue,
                lineArr: [issue.begin_line],
              });
            } else {
              curIssues[sameTitleIndex] && curIssues[sameTitleIndex].lineArr.push(issue.begin_line);
            }
          });
          return (
            <div className="codescan-list-item">
              <div className="codescan-list-item-title">
                <Title trigger={<span>{item}</span>}>{item}</Title>
              </div>
              {!!curIssues &&
                curIssues.map((it) => {
                  return (
                    <div className="codescan-list-item-detail">
                      <div className="codescan-line-info">
                        <Tag color={this.color[it.level]} className="codescan-line-info-tag">
                          {it.level}
                        </Tag>
                        {it.lineArr &&
                          it.lineArr.map((line) => {
                            return (
                              <a
                                href={`#file=${sha1(
                                  it.file_name,
                                )}&line=${line}&side=${side}${range_context}`}
                                onClick={(e) => {
                                  track({
                                    action: 'show_issue_line',
                                    page: 'Repo-MR-changes',
                                    mr_id: codeReviewDetail.id,
                                  });

                                  this.handleLineClick(
                                    e,
                                    `#file=${sha1(
                                      it.file_name,
                                    )}&line=${line}&side=${side}${range_context}`,
                                  );
                                }}
                                className="codescan-line-info-num"
                              >
                                {intl.get(
                                  {
                                    id: 'code-assets.components.codeScan.LineLine',
                                    defaultMessage: '第{line}行',
                                  },
                                  { line },
                                )}
                              </a>
                            );
                          })}
                      </div>
                      <div className="codescan-line-detail one-line-ellipsis" title={it.title}>
                        {it.title}
                      </div>
                    </div>
                  );
                })}
            </div>
          );
        })}
      </div>
    );
  };

  closeCodeScan = () => {
    this.props.updateData({
      isShowCodeScan: false,
    });
  };

  // 过滤掉不在设置中可以开启的服务,比如：流水线
  filterMrBuilds = () => {
    const { mergeRequestBuilds } = this.props;
    if (!(mergeRequestBuilds && mergeRequestBuilds.length)) {
      return [];
    }
    return mergeRequestBuilds.filter((item) => {
      const { task_name } = item;
      return Object.keys(mrTriggerMap).some((key) => {
        return mrTriggerMap[key] === task_name;
      });
    });
  };

  renderTitle = () => {
    const { codeScan } = this.state;
    const curBuilds = this.filterMrBuilds();

    if (!(codeScan && curBuilds && curBuilds.length)) {
      return (
        <span>
          {intl.get({
            id: 'code-assets.components.codeScan.AutomatedScanning',
            defaultMessage: '自动化扫描',
          })}
        </span>
      );
    } else {
      return (
        <div className="codescan-filter-select">
          <Select
            value={this.state.filterId}
            onChange={(value) => {
              this.setState({
                filterId: value,
              });
            }}
            hasBorder={false}
            style={{ minWidth: 100 }}
          >
            {curBuilds.map((item) => {
              return (
                <Select.Option value={item.id} key={item.id} hasBorder={false}>
                  {item.task_name}
                </Select.Option>
              );
            })}
          </Select>
        </div>
      );
    }
  };

  renderContent = () => {
    const { codeScan } = this.state;

    if (codeScan === null) {
      return <ListLoading />;
    } else if (codeScan === false) {
      return (
        <div className="codescan-list-empty">
          <ListEmpty
            image="none"
            content={intl.get({
              id: 'code-assets.components.codeScan.AutomaticScanDisabled',
              defaultMessage: '未开启自动化扫描',
            })}
            description={intl.get({
              id: 'code-assets.components.codeScan.TheAdministratorCanEnableIntegration',
              defaultMessage: '管理员可在 设置-集成与服务 开启',
            })}
            size="small"
            type="card"
            className="no-btns"
          />
        </div>
      );
    } else {
      return <div className="codescan-list-container-body">{this.renderList()}</div>;
    }
  };

  render() {
    const { isShowCodeScan, issueDetailList } = this.props;
    if (!isShowCodeScan || !issueDetailList) {
      return null;
    }

    return (
      <React.Fragment>
        <div className="codescan-list-container">
          <div className={'codescan-list-container-title'}>
            {this.renderTitle()}
            <span className="codescan-list-container-title-close">
              <ButtonIcon name="false-line" text onClick={this.closeCodeScan} />
            </span>
          </div>
          {this.renderContent()}
        </div>
      </React.Fragment>
    );
  }
}
